import { Configuration, OpenAIApi } from 'openai'
import type { ChatMessage } from '@/types'

let openai: OpenAIApi | null = null

export const initOpenAI = (apiKey: string) => {
  const configuration = new Configuration({
    apiKey: apiKey
  })
  openai = new OpenAIApi(configuration)
  return openai
}

export const streamChat = async (
  message: string, 
  context: ChatMessage[],
  onProgress: (text: string) => void
) => {
  if (!openai) {
    throw new Error('OpenAI 未初始化')
  }

  // 转换消息格式
  const messages = context
    .filter(msg => msg.type === 'text')
    .map(msg => ({
      role: msg.role,
      content: msg.content
    }))

  // 添加当前消息
  messages.push({
    role: 'user',
    content: message
  })

  try {
    const response = await openai.createChatCompletion({
      model: 'gpt-3.5-turbo',
      messages,
      stream: true,
      temperature: 0.7,
      max_tokens: 2000
    }, { responseType: 'stream' })

    // 处理流式响应
    const stream = response.data as any
    const reader = stream.getReader()
    const decoder = new TextDecoder()

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      // 解析 SSE 数据
      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')
      const parsedLines = lines
        .map(line => line.replace(/^data: /, '').trim())
        .filter(line => line && line !== '[DONE]')
        .map(line => JSON.parse(line))

      for (const parsed of parsedLines) {
        const text = parsed.choices[0]?.delta?.content || ''
        if (text) {
          onProgress(text)
        }
      }
    }
  } catch (error: any) {
    console.error('OpenAI API 错误:', error)
    throw new Error(error.message || '请求失败')
  }
} 